
import { _decorator, Component, Node, BoxCollider2D, Contact2DType, IPhysics2DContact, director } from 'cc';
import { EnemyControl } from './EnemyControl';
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = BulletControl
 * DateTime = Thu Dec 09 2021 11:31:05 GMT+0800 (中国标准时间)
 * Author = huangsz
 * FileBasename = BulletControl.ts
 * FileBasenameNoExtension = BulletControl
 * URL = db://assets/BulletControl.ts
 * ManualUrl = https://docs.cocos.com/creator/3.3/manual/zh/
 *
 */

@ccclass('BulletControl')
export class BulletControl extends Component {

    @property
    speed: number = 800

    start() {
        const collider: BoxCollider2D = this.getComponent(BoxCollider2D);
        collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
    }

    update(deltaTime: number) {
        const pos = this.node.getPosition()
        pos.y += this.speed * deltaTime
        this.node.setPosition(pos)

        if (pos.y >= 800) {
            this.node.destroy()
        }
    }

    /**
     * 只在两个碰撞体开始接触时被调用一次
     * @param self 
     * @param other 
     * @param contact 
     */
    onBeginContact(self: BoxCollider2D, other: BoxCollider2D, contact: IPhysics2DContact | null) {
        this.node.destroy()
        if (other.tag === 1) {
            other.getComponent(EnemyControl).die()
        }
    }
}
